/**
 *  Copyright 1.12.2003 oliver.keusemann@googlemail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package de.xelerity.helper;

public class HexString {

	private final String hexChar = "0123456789abcdef";
	private StringBuffer buf = new StringBuffer();

	void Convert(int val, int maxNibblesToConvert) {

		buf.setLength(0);

		int v = val;
		for (int i = 0; i < maxNibblesToConvert; ++i) {

			if (v == 0) {

				if (i == 0) {
					buf.insert(0, '0');
				}
				break;
			}

			// Get lowest nibble
			int remainder = v & 0xf;

			// Convert nibble to a character and insert it into the beginning of
			// the string
			buf.insert(0, hexChar.charAt(remainder));

			// Shift the int to the right four bits
			v >>>= 4;
		}
	}

	HexString(int val, int minWidth) {

		Convert(val, minWidth);

		int charsNeeded = minWidth - buf.length();
		for (int i = 0; i < charsNeeded; ++i) {
			buf.insert(0, '0');
		}
	}

	public String getString() {

		return buf.toString();
	}
}